//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package net.mingsoft.basic.action;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.Log;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.mingsoft.base.entity.BaseEntity;
import net.mingsoft.base.entity.ResultData;
import net.mingsoft.basic.annotation.LogAnn;
import net.mingsoft.basic.bean.EUListBean;
import net.mingsoft.basic.biz.IManagerBiz;
import net.mingsoft.basic.biz.IModelBiz;
import net.mingsoft.basic.biz.IRoleModelBiz;
import net.mingsoft.basic.biz.IYmaBiz;
import net.mingsoft.basic.constant.e.BusinessTypeEnum;
import net.mingsoft.basic.constant.e.ModelIsMenuEnum;
import net.mingsoft.basic.entity.ManagerEntity;
import net.mingsoft.basic.entity.ModelEntity;
import net.mingsoft.basic.entity.RoleModelEntity;
import net.mingsoft.basic.entity.YmaEntity;
import net.mingsoft.basic.exception.BusinessException;
import net.mingsoft.basic.strategy.IModelStrategy;
import net.mingsoft.basic.util.BasicUtil;
import net.mingsoft.basic.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.*;
import java.util.stream.Collectors;

@Api(
        tags = {"后端-基础接口"}
)
@Controller
@RequestMapping({"/${ms.manager.path}/basic/yma"})
public class YmaAction extends BaseAction {
    @Autowired
    private IModelBiz modelBiz;
    @Autowired
    private IModelStrategy modelStrategy;
    @Autowired
    private IManagerBiz managerBiz;
    @Autowired
    private IRoleModelBiz roleModelBiz;

    @Autowired
    private IYmaBiz ymaBiz;

    public YmaAction() {
    }

    @ApiIgnore
    @GetMapping({"/index"})
//    @RequiresPermissions({"basic:yma:view"})
    public String index(HttpServletResponse response, HttpServletRequest request, ModelMap mode) {
        List<ModelEntity> parentModelList = this.modelStrategy.list();
        mode.addAttribute("parentModelList", JSONUtil.toJsonStr(parentModelList));
        return "/WEB-INF/manager/basic/yma/index";
    }

    @ApiOperation("菜单列表接口")
    @GetMapping({"/list"})
    @ResponseBody
    public ResultData list(@ModelAttribute @ApiIgnore ModelEntity modelEntity, HttpServletResponse response, HttpServletRequest request, @ApiIgnore ModelMap model) {
        List<YmaEntity> ymaEntityList=ymaBiz.list();



        return ResultData.build().success(ymaEntityList);
    }

    @ApiOperation("菜单子集列表")
    @GetMapping({"/childList"})
    @ApiImplicitParams({@ApiImplicitParam(
            name = "modelTitle",
            value = "菜单名称",
            required = false,
            paramType = "query"
    ), @ApiImplicitParam(
            name = "modelId",
            value = "父级菜单编号",
            required = false,
            paramType = "query"
    )})
//    @RequiresPermissions({"basic:yma:view"})
    @ResponseBody
    public ResultData childList(@ModelAttribute @ApiIgnore ModelEntity modelEntity, HttpServletResponse response, HttpServletRequest request) {
        List<ModelEntity> list = this.modelBiz.queryChildList(modelEntity);
        return ResultData.build().success(list);
    }

    @ApiOperation("菜单导入接口")
    @ApiImplicitParams({@ApiImplicitParam(
            name = "menuStr",
            value = "菜单json",
            required = true,
            paramType = "query"
    ), @ApiImplicitParam(
            name = "modelId",
            value = "父级菜单编号",
            required = true,
            paramType = "query"
    )})
    @LogAnn(
            title = "导入菜单",
            businessType = BusinessTypeEnum.INSERT
    )
    @PostMapping({"/import"})
    @ResponseBody
    public ResultData importMenu(String menuStr, int modelId) {
        if (StringUtils.isBlank(menuStr)) {
            return ResultData.build().error(this.getResString("err.empty", new String[]{this.getResString("menu")}));
        } else {
            try {
                List<ModelEntity> list = JSONUtil.toList(menuStr, ModelEntity.class);
                ManagerEntity manager = BasicUtil.getManager();

                assert manager != null;

                List<String> modelUrlList = new ArrayList();
                List<String> modelTitleList = new ArrayList();
                this.addModelUrlAndTitleForList(list, modelUrlList, modelTitleList);
                LambdaQueryWrapper<ModelEntity> wrapper = null;
                List<ModelEntity> duplicateModelUrls;
                List collect;
                if (CollectionUtil.isNotEmpty(modelTitleList)) {
                    wrapper = new LambdaQueryWrapper();
                    wrapper.in(ModelEntity::getModelTitle, modelTitleList);
                    wrapper.in(ModelEntity::getModelIsMenu, new Object[]{ModelIsMenuEnum.MODEL_MEUN.toInt()});
                    duplicateModelUrls = this.modelBiz.list(wrapper);
                    if (CollectionUtil.isNotEmpty(duplicateModelUrls)) {

                        collect = (List)duplicateModelUrls.stream().map(ModelEntity::getModelUrl).collect(Collectors.toList());
                        Log.get(YmaAction.class).error("以下标题已存在：{}", new Object[]{StringUtils.join(collect, ",")});
                        return ResultData.build().error(this.getResString("err.exist", new String[]{this.getResString("model.title")}) + ": " + StringUtils.join(collect, ","));
                    }
                }

                if (CollectionUtil.isNotEmpty(modelUrlList)) {
                    wrapper = new LambdaQueryWrapper();
                    wrapper.in(ModelEntity::getModelUrl, modelUrlList);
                    duplicateModelUrls = this.modelBiz.list(wrapper);
                    if (CollectionUtil.isNotEmpty(duplicateModelUrls)) {
                        collect = (List)duplicateModelUrls.stream().map(ModelEntity::getModelUrl).collect(Collectors.toList());
                        Log.get(YmaAction.class).error("以下标识已存在：{}", new Object[]{StringUtils.join(collect, ",")});
                        return ResultData.build().error(this.getResString("err.exist", new String[]{this.getResString("model.url")}) + ": " + StringUtils.join(collect, ","));
                    }
                }

                Iterator var12 = list.iterator();

                while(var12.hasNext()) {
                    ModelEntity modelEntity = (ModelEntity)var12.next();
                    if (modelEntity.getModelIsMenu() == 0) {
                        return ResultData.build().error("功能权限按钮不能作为菜单导入!");
                    }

                    this.modelBiz.importModel(modelEntity, manager.getRoleId(), String.valueOf(modelId), modelId);
                }
            } catch (RuntimeException var10) {
                var10.printStackTrace();
                return ResultData.build().error(this.getResString("model.title.or.json"));
            } catch (Exception var11) {
                return ResultData.build().error(this.getResString("err.error", new String[]{this.getResString("menu")}));
            }

            this.modelBiz.updateCache();
            return ResultData.build().success();
        }
    }

    @ApiOperation("获取模块表")
    @ApiImplicitParam(
            name = "id",
            value = "模块的编号",
            required = true,
            paramType = "query"
    )
    @GetMapping({"/get"})
//    @RequiresPermissions({"basic:yma:view"})
    @ResponseBody
    public ResultData get(@ModelAttribute @ApiIgnore ModelEntity modelEntity, HttpServletResponse response, HttpServletRequest request, @ApiIgnore ModelMap model) {
        if (StringUtils.isEmpty(modelEntity.getId())) {
            return ResultData.build().error(this.getResString("err.error", new String[]{this.getResString("model.id")}));
        } else {
            ModelEntity _model = (ModelEntity)this.modelBiz.getEntity(Integer.parseInt(modelEntity.getId()));
            if (_model != null) {
                Map<String, ModelEntity> mode = new HashMap();
                if (_model.getModelId() != null) {
                    ModelEntity parentModel = (ModelEntity)this.modelBiz.getEntity(_model.getModelId());
                    mode.put("parentModel", parentModel);
                }

                mode.put("model", _model);
                return ResultData.build().success(mode);
            } else {
                return ResultData.build().success(_model);
            }
        }
    }

    @ApiOperation("保存模块表实体")
    @ApiImplicitParams({@ApiImplicitParam(
            name = "modelTitle",
            value = "模块的标题",
            required = true,
            paramType = "query"
    ), @ApiImplicitParam(
            name = "modelCode",
            value = "模块编码",
            required = false,
            paramType = "query"
    ), @ApiImplicitParam(
            name = "modelId",
            value = "模块父id",
            required = false,
            paramType = "query"
    ), @ApiImplicitParam(
            name = "modelUrl",
            value = "链接地址",
            required = false,
            paramType = "query"
    ), @ApiImplicitParam(
            name = "modelDatetime",
            value = "发布时间",
            required = false,
            paramType = "query"
    ), @ApiImplicitParam(
            name = "modelIcon",
            value = "模块图标",
            required = false,
            paramType = "query"
    ), @ApiImplicitParam(
            name = "modelSort",
            value = "模块排序",
            required = false,
            paramType = "query"
    ), @ApiImplicitParam(
            name = "modelIsMenu",
            value = "是否是菜单",
            required = false,
            paramType = "query"
    ), @ApiImplicitParam(
            name = "isChild",
            value = "菜单类型",
            required = false,
            paramType = "query"
    ), @ApiImplicitParam(
            name = "modelParentIds",
            value = "父级编号集合",
            required = false,
            paramType = "query"
    )})
    @LogAnn(
            title = "保存模块表实体",
            businessType = BusinessTypeEnum.INSERT
    )
    @PostMapping({"/save"})
    @ResponseBody
//    @RequiresPermissions({"basic:yma:save"})
    public ResultData save(@ModelAttribute @ApiIgnore ModelEntity model, HttpServletResponse response, HttpServletRequest request) {
        if (StringUtils.isBlank(model.getModelTitle())) {
            return ResultData.build().error(this.getResString("err.empty", new String[]{this.getResString("model.title")}));
        } else if (!StringUtil.checkLength(model.getModelTitle() + "", 1, 10)) {
            return ResultData.build().error(this.getResString("err.length", new String[]{this.getResString("model.title"), "1", "10"}));
        } else {
            if (model.getModelIsMenu() == ModelIsMenuEnum.MODEL_MEUN.toInt()) {
                LambdaQueryWrapper<ModelEntity> wrapper = new LambdaQueryWrapper();
                wrapper.eq(ModelEntity::getModelTitle, model.getModelTitle())
                .eq(ModelEntity::getModelIsMenu, ModelIsMenuEnum.MODEL_MEUN.toInt());
                List<ModelEntity> list = this.modelBiz.list(wrapper);
                if (CollectionUtil.isNotEmpty(list)) {
                    return ResultData.build().error(this.getResString("err.exist", new String[]{this.getResString("model.title")}));
                }
            }

            if (model.getModelIsMenu() == ModelIsMenuEnum.MODEL_NOTMENU.toInt()) {
                model.setModelUrl(model.getModelUrl().trim());
                if (StringUtils.isBlank(model.getModelUrl())) {
                    return ResultData.build().error(this.getResString("err.empty", new String[]{this.getResString("model.url")}));
                }
                LambdaQueryWrapper<ModelEntity> wrapper=new LambdaQueryWrapper<>();
                wrapper.eq(ModelEntity::getModelUrl, model.getModelUrl());
                List<ModelEntity> modelList = this.modelBiz.list(wrapper);
                if (CollectionUtil.isNotEmpty(modelList)) {
                    return ResultData.build().error(this.getResString("err.exist", new String[]{this.getResString("model.url")}));
                }
            }

            model.setModelDatetime(new Timestamp(System.currentTimeMillis()));
            if (!StringUtils.isBlank(model.getModelIcon())) {
                model.setModelIcon(model.getModelIcon().replace("|", ""));
            }

            ModelEntity modelEntity;
            if (StringUtils.isNotBlank(model.getModelCode())) {
                modelEntity = this.modelBiz.getEntityByModelCode(model.getModelCode());
                if (modelEntity != null) {
                    return ResultData.build().error(this.getResString("err.exist", new String[]{this.getResString("modelCode")}));
                }
            }

            if (model.getModelSort() == null) {
                model.setModelSort(0);
            }

            if (model.getModelId() != null) {
                modelEntity = (ModelEntity)this.modelBiz.getById(model.getModelId());
                if (StringUtils.isBlank(modelEntity.getModelParentIds())) {
                    model.setModelParentIds(model.getModelId().toString());
                } else {
                    model.setModelParentIds(modelEntity.getModelParentIds() + "," + model.getModelId().toString());
                }
            }

            this.modelBiz.save(model);
            if (StringUtils.isNotEmpty(model.getId())) {
                ManagerEntity manager = BasicUtil.getManager();

                assert manager != null;

                List<RoleModelEntity> roleModels = new ArrayList();
                String[] var6 = manager.getRoleIds().split(",");
                int var7 = var6.length;

                for(int var8 = 0; var8 < var7; ++var8) {
                    String roleId = var6[var8];
                    RoleModelEntity roleModel = new RoleModelEntity();
                    roleModel.setModelId(Integer.parseInt(model.getId()));
                    roleModel.setRoleId(Integer.parseInt(roleId));
                    roleModels.add(roleModel);
                }

                this.roleModelBiz.saveBatch(roleModels, roleModels.size());
            }

            this.modelBiz.updateCache();
            return ResultData.build().success(model.getId());
        }
    }

    @ApiOperation("批量删除模块表")
    @ApiImplicitParam(
            name = "ids",
            value = "模块编号，多个以逗号隔开",
            required = false,
            paramType = "query"
    )
    @LogAnn(
            title = "批量删除模块表",
            businessType = BusinessTypeEnum.DELETE
    )
    @PostMapping({"/delete"})
    @ResponseBody
//    @RequiresPermissions({"basic:yma:del"})
    public ResultData delete(HttpServletResponse response, HttpServletRequest request) {
        int[] ids = BasicUtil.getInts("ids", ",");
        this.modelBiz.delete(ids);
        return ResultData.build().success();
    }

    @ApiOperation("更新模块表信息模块表")
    @ApiImplicitParams({@ApiImplicitParam(
            name = "id",
            value = "模块的编号",
            required = true,
            paramType = "query"
    ), @ApiImplicitParam(
            name = "modelTitle",
            value = "模块的标题",
            required = true,
            paramType = "query"
    ), @ApiImplicitParam(
            name = "modelCode",
            value = "模块编码",
            required = false,
            paramType = "query"
    ), @ApiImplicitParam(
            name = "modelId",
            value = "模块父id",
            required = false,
            paramType = "query"
    ), @ApiImplicitParam(
            name = "modelUrl",
            value = "链接地址",
            required = false,
            paramType = "query"
    ), @ApiImplicitParam(
            name = "modelDatetime",
            value = "发布时间",
            required = false,
            paramType = "query"
    ), @ApiImplicitParam(
            name = "modelIcon",
            value = "模块图标",
            required = false,
            paramType = "query"
    ), @ApiImplicitParam(
            name = "modelSort",
            value = "模块排序",
            required = false,
            paramType = "query"
    ), @ApiImplicitParam(
            name = "modelIsMenu",
            value = "是否是菜单",
            required = false,
            paramType = "query"
    ), @ApiImplicitParam(
            name = "isChild",
            value = "菜单类型",
            required = false,
            paramType = "query"
    ), @ApiImplicitParam(
            name = "modelParentIds",
            value = "父级编号集合",
            required = false,
            paramType = "query"
    )})
    @LogAnn(
            title = "更新模块表信息模块表",
            businessType = BusinessTypeEnum.UPDATE
    )
    @PostMapping({"/update"})
//    @RequiresPermissions({"basic:yma:update"})
    @ResponseBody
    public ResultData update(@ModelAttribute @ApiIgnore ModelEntity model, HttpServletResponse response, HttpServletRequest request) {
        if (StringUtil.isBlank(model.getModelTitle())) {
            return ResultData.build().error(this.getResString("err.empty", new String[]{this.getResString("model.title")}));
        } else if (!StringUtil.checkLength(model.getModelTitle() + "", 1, 10)) {
            return ResultData.build().error(this.getResString("err.length", new String[]{this.getResString("model.title"), "1", "10"}));
        } else {
            List modelList;
            if (model.getModelIsMenu() == ModelIsMenuEnum.MODEL_MEUN.toInt()) {
                LambdaQueryWrapper<ModelEntity> wrapper = new LambdaQueryWrapper();
                wrapper.eq(ModelEntity::getModelTitle, model.getModelTitle())
                        .eq(ModelEntity::getModelIsMenu, ModelIsMenuEnum.MODEL_MEUN.toInt());
                modelList = this.modelBiz.list(wrapper);
                if (CollectionUtil.isNotEmpty(modelList) && (modelList.size() > 1 || !((ModelEntity)modelList.get(0)).getId().equals(model.getId()))) {
                    return ResultData.build().error(this.getResString("err.exist", new String[]{this.getResString("model.title")}));
                }
            }

            ModelEntity _model = (ModelEntity)this.modelBiz.getEntity(Integer.parseInt(model.getId()));
            if (_model.getModelIsMenu() == 1 && model.getModelIsMenu() == 0) {
                return ResultData.build().error(this.getResString("model.is.menu"));
            } else {
                if (model.getModelIsMenu() == ModelIsMenuEnum.MODEL_NOTMENU.toInt()) {
                    model.setModelUrl(model.getModelUrl().trim());
                    if (StringUtils.isBlank(model.getModelUrl())) {
                        return ResultData.build().error(this.getResString("err.empty", new String[]{this.getResString("model.url")}));
                    }
                    LambdaQueryWrapper<ModelEntity> wrapper=new LambdaQueryWrapper();
                    wrapper.eq(ModelEntity::getModelUrl, model.getModelUrl());
                    modelList = this.modelBiz.list(wrapper);
                    if (CollectionUtil.isNotEmpty(modelList) && !((ModelEntity)modelList.get(0)).getId().equals(model.getId())) {
                        return ResultData.build().error(this.getResString("err.exist", new String[]{this.getResString("model.url")}));
                    }
                }

                if (!StringUtil.isBlank(model.getModelIcon())) {
                    model.setModelIcon(model.getModelIcon().replace("|", ""));
                }

                this.modelBiz.updateEntity(model);
                return ResultData.build().success(model.getId());
            }
        }
    }

    @ApiOperation("根据管理员ID查询模块集合")
    @ApiImplicitParam(
            name = "managerId",
            value = "管理员id",
            required = true,
            paramType = "path"
    )
    @GetMapping({"/{managerId}/queryModelByRoleId"})
    @ResponseBody
    public ResultData queryModelByRoleId(@PathVariable @ApiIgnore int managerId, HttpServletRequest request, HttpServletResponse response) {
        ManagerEntity manager = (ManagerEntity)this.managerBiz.getEntity(managerId);
        if (manager == null) {
            return ResultData.build().error();
        } else {
            HashSet<ModelEntity> modelSet = new HashSet();
            String[] var6 = manager.getRoleIds().split(",");
            int var7 = var6.length;

            for(int var8 = 0; var8 < var7; ++var8) {
                String roleId = var6[var8];
                modelSet.addAll(this.modelBiz.queryModelByRoleId(Integer.parseInt(roleId)));
            }

            List<ModelEntity> modelList = new ArrayList(modelSet);
            return ResultData.build().success(modelList);
        }
    }

    @ApiOperation("查询模块表列表")
    @ApiImplicitParam(
            name = "roleId",
            value = "角色编号",
            required = true,
            paramType = "query"
    )
    @GetMapping({"/ymaList"})
    @ResponseBody
    public ResultData modelList(@ModelAttribute @ApiIgnore ModelEntity modelEntity, HttpServletResponse response, HttpServletRequest request, @ApiIgnore ModelMap model) {
        int roleId = BasicUtil.getInt("roleId");
        ManagerEntity managerSession = BasicUtil.getManager();
        boolean updateFlag = roleId != 0;
        List<ModelEntity> modelList = this.modelStrategy.list();
        List<ModelEntity> _modelList = new ArrayList();
        List<RoleModelEntity> roleModelList = new ArrayList();
        if (roleId > 0) {
            roleModelList = this.roleModelBiz.queryByRoleId(roleId);
        } else {
            HashSet<RoleModelEntity> roleSet = new HashSet();
            String[] var12 = managerSession.getRoleIds().split(",");
            int var13 = var12.length;

            for(int var14 = 0; var14 < var13; ++var14) {
                String id = var12[var14];
                roleSet.addAll(this.roleModelBiz.queryByRoleId(Integer.parseInt(id)));
            }

            ((List)roleModelList).addAll(roleSet);
        }

        List<ModelEntity> childModelList = new ArrayList();
        Iterator var19 = modelList.iterator();

        while(var19.hasNext()) {
            BaseEntity base = (BaseEntity)var19.next();
            ModelEntity _model = (ModelEntity)base;
            if (_model.getModelIsMenu() == 1) {
                _model.setModelChildList(new ArrayList());
                _modelList.add(_model);
            } else if (_model.getModelIsMenu() == 0) {
                childModelList.add(_model);
            }
        }

        var19 = _modelList.iterator();

        label55:
        while(var19.hasNext()) {
            ModelEntity _modelEntity = (ModelEntity)var19.next();
            Iterator var24 = childModelList.iterator();

            while(true) {
                ModelEntity childModel;
                do {
                    if (!var24.hasNext()) {
                        continue label55;
                    }

                    childModel = (ModelEntity)var24.next();
                } while(childModel.getModelId() != Integer.parseInt(_modelEntity.getId()));

                _modelEntity.getModelChildList().add(childModel);
                Iterator var16 = ((List)roleModelList).iterator();

                while(var16.hasNext()) {
                    RoleModelEntity roleModelEntity = (RoleModelEntity)var16.next();
                    if (roleModelEntity.getModelId() == Integer.parseInt(childModel.getId()) && updateFlag) {
                        childModel.setChick(1);
                    }
                }
            }
        }

        EUListBean _list = new EUListBean(_modelList, _modelList.size());
        return ResultData.build().success(_list);
    }

    private void addModelUrlAndTitleForList(List<ModelEntity> modelEntityList, List<String> modelUrlList, List<String> modelTitleList) {
        if (!CollectionUtil.isEmpty(modelEntityList) && modelUrlList != null && modelTitleList != null) {
            Iterator var4 = modelEntityList.iterator();

            while(var4.hasNext()) {
                ModelEntity model = (ModelEntity)var4.next();
                if (!StringUtil.checkLength(model.getModelTitle() + "", 1, 20)) {
                    throw new BusinessException(this.getResString("err.length", new String[]{this.getResString("model.title"), "1", "20"}));
                }

                if (model.getModelIsMenu() == ModelIsMenuEnum.MODEL_NOTMENU.toInt()) {
                    if (StringUtils.isBlank(model.getModelUrl())) {
                        throw new BusinessException(this.getResString("err.empty", new String[]{this.getResString("model.url")}));
                    }

                    model.setModelUrl(model.getModelUrl().trim());
                    modelUrlList.add(model.getModelUrl());
                } else {
                    modelTitleList.add(model.getModelTitle());
                }

                if (CollectionUtil.isNotEmpty(model.getModelChildList())) {
                    this.addModelUrlAndTitleForList(model.getModelChildList(), modelUrlList, modelTitleList);
                }
            }

        }
    }
}
